package cn.sccl.common.util;

import org.springframework.util.StringUtils;

import java.io.*;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 杨浩宇 on 2015-11-27.
 */
public class StrUtils {
    /**
     * ********************************************************************
     * 驼峰式命名转换
     * ********************************************************************
     */
    private static final char SEPARATOR = '_';

    /**
     * 将驼峰式命名的字符串转换为_的形式
     * 如userName 转换为 user_name
     *
     * @param name
     * @return
     */
    public static String underscoreName(String name) {
        if (!StringUtils.hasLength(name)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        result.append(name.substring(0, 1).toLowerCase());
        for (int i = 1; i < name.length(); i++) {
            String s = name.substring(i, i + 1);
            String slc = s.toLowerCase();
            if (!s.equals(slc)) {
                result.append("_").append(slc);
            } else {
                result.append(s);
            }
        }
        return result.toString();

    }

    /**
     * 驼峰式字符转换为下杠形式
     * ISOCertifiedStaff -> iso_certified_staff
     * CertifiedStaff -> certified_staff
     * UserID -> user_id
     *
     * @param s 驼峰式字符串
     * @return 带下杠的字符串
     */
    public static String toUnderlineName(String s) {
        if (s == null) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            boolean nextUpperCase = true;

            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }

            if ((i >= 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    if (i > 0) sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }

            sb.append(Character.toLowerCase(c));
        }

        return sb.toString();
    }

    /**
     * 下杠式字符转换为驼峰形式
     * iso_certified_staff -> isoCertifiedStaff
     * certified_staff -> certifiedStaff
     * user_id -> userId
     *
     * @param s 带下杠的字符串
     * @return 驼峰式字符串
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }

        s = s.toLowerCase();

        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    /**
     * 下杠式字符转换为驼峰形式，但首字符大写
     * iso_certified_staff -> IsoCertifiedStaff
     * certified_staff -> CertifiedStaff
     * user_id -> UserId
     *
     * @param s 带下杠的字符串
     * @return 驼峰式字符串
     */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }


    /*********************************************************
     * 字符串首字母处理
     ********************************************************/
    /**
     * 字符串首字母小写
     *
     * @param s
     * @return
     */
    public static String toLowerFirst(String s) {
        char[] chars = new char[1];
        chars[0] = s.charAt(0);
        String temp = new String(chars);
        if (chars[0] >= 'A' && chars[0] <= 'Z') {//当为字母时，则转换为小写
            return s.replaceFirst(temp, temp.toLowerCase());
        }
        return s;
    }

    /**
     * 字符串首字母大写
     *
     * @param s
     * @return
     */
    public static String toUpperFirst(String s) {
        char[] chars = new char[1];
        chars[0] = s.charAt(0);
        String temp = new String(chars);
        if (chars[0] >= 'a' && chars[0] <= 'z') {//当为字母时，则转换为小写
            s.replaceFirst(temp, temp.toUpperCase());
        }
        return s;
    }


    /**
     * InputStream 转String
     *
     * @param blob
     * @return
     * @throws IOException
     */
    public static String blob2String(Blob blob) throws IOException, SQLException {
        InputStream is = blob.getBinaryStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }
    /**
     * oracle.sql.Clob类型转换成String类型
     *
     * @param clob
     * @return
     */
    public static String clob2String(Clob clob) {
        if (clob == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer(65535);// 64K
        Reader clobStream = null;// 创建一个输入流对象
        try {
            clobStream = clob.getCharacterStream();
            char[] b = new char[60000];// 每次获取60K
            int i = 0;
            while ((i = clobStream.read(b)) != -1) {
                sb.append(b, 0, i);
            }
        } catch (Exception ex) {
            sb = null;
        } finally {
            try {
                if (clobStream != null)
                    clobStream.close();
            } catch (Exception e) {
            }
        }
        if (sb == null)
            return null;
        else
            return sb.toString();
    }

    public static String getMD5(String data) {
        return data;
    }

    public static String generateShortUuid() {
//        String sql = "select uuid_short()";
//        DataSet ds = this.dataBase.query(sql);
//        DataRow dr = ds.getRow(0);
//        return dr.getString(0);
//        String sdf = new SimpleDateFormat("yyyyMMddHHMMSS").format(new Date());
        String trandNo = String.valueOf((Math.random() * 9 + 1) * 1000000);
        trandNo = trandNo.replace(".","");
        return trandNo;
    }

    /**
     * 将字节数组转化为对象
     *
     * @param bytes
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     * @author lichmama
     */
    @SuppressWarnings("unchecked")
    public static <T> T bytesToObject(byte[] bytes) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            bais.close();
            ois.close();
            return (T) object;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将对象转化为字节数组
     *
     * @param object
     * @return
     * @throws IOException
     * @author lichmama
     */
    public static byte[] objectToBytes(Object object) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            baos.close();
            oos.close();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
